using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using PSLibrary = Microsoft.Office.Project.Server.Library;
using System.Collections.ObjectModel;
using Microsoft.Office.Project.EPMSync.Config.Editor.Properties;
using Microsoft.Office.Project.EPMSync.Config.Library;
using System.Globalization;

namespace Microsoft.Office.Project.EPMSync.Config.Editor
{
    public partial class FormEditExcludedProjects : Form
    {
        private Dictionary<Guid, string> _projectList;
        FormMain ptrMain;
        private int _countProjects;

        public FormEditExcludedProjects(FormMain main)
        {
            InitializeComponent();
            ptrMain = main;
        }
        #region Create Lists
        public bool SetLists(string serverUrl, Collection<Guid> excludedProjects)
        {
            try
            {
                ReadProjectList(serverUrl);
            }
            catch( Exception ex)
            {
                RightAwareMessageBox.Show(ex.Message, Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return false;
            }

            if (_countProjects > 0)
            {
                foreach (string projectName in _projectList.Values)
                {
                    listBoxAvailable.Items.Add(projectName);
                }
                foreach (Guid project in excludedProjects)
                {
                    AddToExcludedList(project);
                }
                return true;
            }
            else
            {
                RightAwareMessageBox.Show(Resources.EmptyProjectList, Resources.EditorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); 
                this.Close();
                return false;
            }
        }

         private void ReadProjectList(string serverURL)
        {
            try
            {
                ProjectWS.Project projWebSvc = new ProjectWS.Project();
                projWebSvc.CookieContainer = new CookieContainer();
                projWebSvc.Credentials = CredentialCache.DefaultCredentials;
                projWebSvc.Url = WebServiceUrl.Project(serverURL);
                //projWebSvc.Url = SetProjectURL(serverURL);

                _projectList = new Dictionary<Guid, string>();
                ProjectWS.ProjectDataSet pds;

                pds = projWebSvc.ReadProjectStatus(Guid.Empty, ProjectWS.DataStoreEnum.PublishedStore, string.Empty, (int)PSLibrary.Project.ProjectType.Project);
                foreach (ProjectWS.ProjectDataSet.ProjectRow pr in pds.Project)
                {
                    _countProjects++;
                    _projectList.Add(pr.PROJ_UID, String.Format(CultureInfo.InvariantCulture, "P  - {0}", pr.PROJ_NAME));
                }
                pds = projWebSvc.ReadProjectStatus(Guid.Empty, ProjectWS.DataStoreEnum.PublishedStore, string.Empty,(int)PSLibrary.Project.ProjectType.MasterProject);
                foreach (ProjectWS.ProjectDataSet.ProjectRow pr in pds.Project)
                {
                    _countProjects++;
                    _projectList.Add(pr.PROJ_UID, String.Format(CultureInfo.InvariantCulture, "MP - {0}", pr.PROJ_NAME));
                }
                pds = projWebSvc.ReadProjectStatus(Guid.Empty, ProjectWS.DataStoreEnum.PublishedStore, string.Empty, (int)PSLibrary.Project.ProjectType.LightWeightProject);
                foreach (ProjectWS.ProjectDataSet.ProjectRow pr in pds.Project)
                {
                    _countProjects++;
                    _projectList.Add(pr.PROJ_UID, String.Format(CultureInfo.InvariantCulture, "LW - {0}", pr.PROJ_NAME));
                }
                pds = projWebSvc.ReadProjectStatus(Guid.Empty, ProjectWS.DataStoreEnum.PublishedStore, string.Empty, (int)PSLibrary.Project.ProjectType.InsertedProject);
                foreach (ProjectWS.ProjectDataSet.ProjectRow pr in pds.Project)
                {
                    _countProjects++;
                    _projectList.Add(pr.PROJ_UID, String.Format(CultureInfo.InvariantCulture, "IP - {0}", pr.PROJ_NAME));
                }
            }
            catch (Exception)
            {
                throw new Exception(Resources.ProjectListError);
            }

        }

        //private static string SetProjectURL(string PSInstance)
        //{
        //    if (!PSInstance.EndsWith("/"))
        //        PSInstance += "/";
        //    return PSInstance + "_vti_bin/psi/project.asmx";
        //}

       #endregion

        #region List Utility Methods
        private void AddToExcludedList(Guid excludedProject)
        {
            listBoxAvailable.Items.Remove(_projectList[excludedProject]);
            listBoxExcluded.Items.Add(_projectList[excludedProject]);
        }

        private void RemoveFromExcludedList(Guid excludedProject)
        {
            listBoxAvailable.Items.Add(_projectList[excludedProject]);
            listBoxExcluded.Items.Remove(_projectList[excludedProject]);
        }

        private Guid getProjectID(string projectName)
        {
            foreach (KeyValuePair<Guid, string> kvp in _projectList)
            {
                if (kvp.Value == projectName)
                {
                    return kvp.Key;
                }
            }

            // A valid project was not found in the list
            return Guid.Empty;

        }

        #endregion

        #region Button Events
        private void buttonSave_Click(object sender, EventArgs e)
        {
            Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            Collection<Guid> excludedProjects = new Collection<Guid>();
            foreach (string projectName in listBoxExcluded.Items)
            {
                excludedProjects.Add(getProjectID(projectName));
            }
            ptrMain.UpdateExcludedProjects(excludedProjects);
            Cursor.Current = System.Windows.Forms.Cursors.Default;

            this.Close();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonAddToExcluded_Click(object sender, EventArgs e)
        {
            if (listBoxAvailable.SelectedItem != null)
                AddToExcludedList(getProjectID(listBoxAvailable.SelectedItem.ToString()));
        }

        private void buttonRemoveFromExcluded_Click(object sender, EventArgs e)
        {
            if (listBoxExcluded.SelectedItem != null)
                RemoveFromExcludedList(getProjectID(listBoxExcluded.SelectedItem.ToString()));
        }

        #endregion

    }
}